import React, {FormEvent} from "react";
import {useAuth} from "../context/auth-context";
import {Button, Form, Input} from "antd";
import {LongButton} from "./index";
import { useAsync } from "utils/use-async";


export const RegisterScreen = ({onError}: { onError: (error: Error) => void }) => {
    const {register, user} = useAuth()
    const{run,isLoading}=useAsync(undefined,{throwOnError:true})
    // const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    //     // event.preventDefault(); //阻止表单提交
    //     const username = (event.currentTarget.elements[0] as HTMLInputElement)
    //         .value;
    //     const password = (event.currentTarget.elements[1] as HTMLInputElement)
    //         .value;
    //     register({username, password});
    // };
    const handleSubmit = async ({cpassword, ...values}: { username: string, password: string, cpassword: string }) => {
        if (cpassword !== values.password) {
            onError(new Error('请确认两次输入的密码相同'))
            return
        }
        try {
            await run(register(values))
        } catch (e) {
            console.log(e)
            onError(e)
        }
    }
    return (
        <Form onFinish={handleSubmit}>
            <Form.Item name={'username'} rules={[{required: true, message: '请输入用户名'}]}>
                <Input type={"text"} placeholder={'用户名'} id={"username"}/>
            </Form.Item>
            <Form.Item name={'password'} rules={[{required: true, message: '请输入用户密码'}]}>
                <Input type={"password"} placeholder={'密码'} id={"password"}/>
            </Form.Item>
            <Form.Item name={'cpassword'} rules={[{required: true, message: '请确认密码'}]}>
                <Input type={"password"} placeholder={'确认密码'} id={"cpassword"}/>
            </Form.Item>
            <Form.Item>
                <LongButton loading={isLoading} type={"primary"} htmlType="submit">注册</LongButton>
            </Form.Item>
        </Form>
    )
}
